﻿#include "XAudioPlay.h"


XAudioPlay *XAudioPlay::init()
{
    static XAudioPlay cap;
    return &cap;
}

bool XAudioPlay::start()
{
    stop();
    QMutexLocker locker(&_mutex);

    QAudioFormat fmt;
    fmt.setSampleRate(_sampleRate);
    fmt.setSampleSize(_sampleSize);
    fmt.setChannelCount(_channel);
    fmt.setCodec(_codec);
    fmt.setByteOrder(QAudioFormat::LittleEndian);
    fmt.setSampleType(QAudioFormat::UnSignedInt);

    _output = new QAudioOutput(fmt);
    _io = _output->start();

    return true;
}

void XAudioPlay::stop()
{
    QMutexLocker locker(&_mutex);

    if(_output)
    {
        _output->stop();
        delete _output;
        _output = NULL;
        _io = NULL;
    }
}

void XAudioPlay::play(bool isPlay)
{
    QMutexLocker locker(&_mutex);

    if(!_output) return;

    isPlay ? _output->resume() : _output->suspend();
}

bool XAudioPlay::write(const char *data, int datasize)
{
    QMutexLocker locker(&_mutex);

    if(_io){
        _io->write(data,datasize);
        return true;
    }

    return false;
}

int XAudioPlay::getFree()
{
    QMutexLocker locker(&_mutex);

    if(!_output) return 0;

    return _output->bytesFree();

}

XAudioPlay::XAudioPlay()
{

}
